import React, { useEffect, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { ScrollView, StyleSheet } from 'react-native';
import Field from '../../../component/Field.tsx';
import { Button, Switch, Text, useToast, View } from 'native-base';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useReactive } from 'ahooks';
import validateInput from '../../../utils/ValidateInput.ts';
import { useSelector } from 'react-redux';
import { RootState } from '../../../redux/store.ts';
import UserRequest from '../../../request/userRequest.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import to from '../../../utils/to.ts';

interface IEmergencyContactProps {
  navigation: NavigationProp<any, 'emergencyContact'>;
  route: RouteProp<any, 'emergencyContact'>;
}
interface IState {
  [key: string]: string | number;
  oneName: string;
  onePhone: string;
  threeName: string;
  threePhone: string;
  twoName: string;
  twoPhone: string;
  helpFlag: number;
}
const EmergencyContact: React.FC<IEmergencyContactProps> = ({ navigation, route }) => {
  const state = useReactive<IState>({ oneName: '', onePhone: '', threeName: '', threePhone: '', twoName: '', twoPhone: '', helpFlag: 0 });
  const [errorValidate, setErrorValidate] = useState('');
  const toast = useToast();
  const userInfo = useSelector((state: RootState) => state.userInfo);

  useEffect(() => {
    Loading.show('加载中');
    UserRequest.GetUserContact({ userId: userInfo.userId })
      .then((res) => {
        Loading.hide();
        ['oneName', 'onePhone', 'threeName', 'threePhone', 'twoName', 'twoPhone', 'helpFlag'].forEach((item) => {
          state[item] = res.data[item];
        });
      })
      .catch(() => Loading.hide());
  }, []);

  /**
   * 保存
   */
  const handleSubmit = async () => {
    if (errorValidate) {
      toast.show({ description: errorValidate });
      return;
    }
    Loading.show('保存中...');
    const [err] = await to(UserRequest.UpdateUserContact({ ...state, userId: userInfo.userId }));
    Loading.hide();
    if (err) return;
    toast.show({ description: '保存成功' });
    navigation.goBack();
  };

  /**
   * switch 开关
   * @param value
   */
  const handleSwitchValueChange = (value: boolean) => {
    UserRequest.UpdateHelpFlag({ helpFlag: value ? 1 : 0, userId: userInfo.userId })
      .then(() => {
        toast.show({ description: value ? '开通邻里互助成功' : '已关闭邻里互助功能' });
        state.helpFlag = value ? 1 : 0;
      })
      .catch(() => {
        state.helpFlag = value ? 0 : 1;
      });
  };

  return (
    <React.Fragment>
      <ScrollView style={styles.root} contentContainerStyle={{ paddingBottom: 60 }}>
        <View style={styles.card}>
          <View style={{ paddingVertical: 12, paddingHorizontal: 2, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text fontWeight={'bold'}>开通邻里互助</Text>
            <Switch size={'lg'} colorScheme="emerald" value={state.helpFlag === 1} onValueChange={handleSwitchValueChange} />
          </View>
        </View>
        <View style={styles.title}>
          <Text fontSize={16} color={'red.500'}>
            第一紧急联系人
          </Text>
        </View>
        <View style={styles.card}>
          <Field placeholder={'请输入姓名'} label={'姓名'} value={state.oneName} onChangeText={(text) => (state.oneName = text)} />
          <Field placeholder={'请输入手机号'} inputNumber label={'手机号'} value={state.onePhone} validate={(value) => setErrorValidate(validateInput('手机号', value, ['phone']))} onChangeText={(text) => (state.onePhone = text)} />
        </View>
        <View style={styles.title}>
          <Text fontSize={16} color={'green.500'}>
            第二紧急联系人
          </Text>
        </View>
        <View style={styles.card}>
          <Field placeholder={'请输入姓名'} label={'姓名'} value={state.twoName} onChangeText={(text) => (state.twoName = text)} />
          <Field placeholder={'请输入手机号'} inputNumber label={'手机号'} value={state.twoPhone} validate={(value) => setErrorValidate(validateInput('手机号', value, ['phone']))} onChangeText={(text) => (state.twoPhone = text)} />
        </View>
        <View style={styles.title}>
          <Text fontSize={16} color={'blue.500'}>
            第三紧急联系人
          </Text>
        </View>
        <View style={styles.card}>
          <Field placeholder={'请输入姓名'} label={'姓名'} value={state.threeName} onChangeText={(text) => (state.threeName = text)} />
          <Field placeholder={'请输入手机号'} inputNumber label={'手机号'} value={state.threePhone} validate={(value) => setErrorValidate(validateInput('手机号', value, ['phone']))} onChangeText={(text) => (state.threePhone = text)} />
        </View>

        <Button bg={CommonStyle.mainColor} _pressed={{ bg: CommonStyle.btnSelectMainColor }} marginTop={'8'} onPress={handleSubmit}>
          保存地址
        </Button>
      </ScrollView>
    </React.Fragment>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1, padding: 16 },
  title: { paddingHorizontal: 0, paddingVertical: 16 },
  card: { paddingHorizontal: 16, borderRadius: 8, backgroundColor: '#fff' },
});

export default EmergencyContact;
